package nl.dds.sandr.LoesjeOfTheDay;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

public class LOTDAppWidgetProvider extends AppWidgetProvider {
    /** Called when the activity is first created. */
    @Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        context.startService(new Intent(context, UpdateService.class));
    }

    public static class UpdateService extends Service {
    	
    	private static final String TAG = "LOTDUpdateService";
    	
        @Override
        public void onStart(Intent intent, int startId) {
        	//Log.d(TAG,"Starting UpdateService.");
        	RemoteViews views = new RemoteViews(getPackageName(), R.layout.lotdwidget);
        	
        	HttpURLConnection urlConnection = null;
            try {
              URL url = new URL("http://www.loesje.nl/pix/hlactie.gif");
              urlConnection = (HttpURLConnection) url.openConnection();
              BufferedInputStream bis = new BufferedInputStream(urlConnection.getInputStream());
              Bitmap bmp = BitmapFactory.decodeStream(bis);
              //if (bmp==null) {Log.d(TAG,"bmp null");};
              views.setImageViewBitmap(R.id.widgetImageView, bmp);
              //Log.d(TAG,"setImageView performed");
            } catch (MalformedURLException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();         
            } catch (IOException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		} finally {
              urlConnection.disconnect();
            }        
                
            // Push update for this widget to the home screen
            ComponentName thisWidget = new ComponentName(this, LOTDAppWidgetProvider.class); // assuming there is only one?
            AppWidgetManager manager = AppWidgetManager.getInstance(this);
            manager.updateAppWidget(thisWidget, views);
            
            stopSelf();
        }

		@Override
		public IBinder onBind(Intent arg0) {
			// TODO Auto-generated method stub
			return null;
		}

    }
}